<?php
/*
 +----------------------------------------------------------------------
 | TEMMOKUMVC [ NO BEST , ONLY BETTER ]
 +----------------------------------------------------------------------
 | Copyright (c) 2018~2019 https://www.temmoku.cn All rights reserved.
 +----------------------------------------------------------------------
 | Author: 张宗强 Email:webmaster@temmoku.cn QQ:158726877 516669373 TEL:17895221001 微信:temmokumvc
 +---------------------------------------------------------------------- 
*/
namespace plugin\wechat\home\controller;
use \temmoku\db;
use \temmoku\controller;
use \temmoku\lib\cookie;
use \plugin\wechat\public_class\wechat;
class index extends controller{

	//判断是介入还是用户  只有第一次介入的时候才会返回echostr
   	public function index()
    {	
    	
    	$power=$this->checkSignature();
    	if(!$power){
    		exit;
    	}elseif($_GET["echostr"]){
    		ob_clean();
	        echo $_GET["echostr"];
	        $time= microtime(TRUE)-$GLOBALS['_beginTime'];
	        $content= 'time:'.$time.'REQUEST_METHOD:'.$_SERVER['REQUEST_METHOD']."\n".$_SERVER['SERVER_NAME']."\n".$_SERVER['HTTP_X_REWRITE_URL']."\n--------------------------------------\n";
	        write_file(APP_PATH.'runtime/tmp/weixin.txt',$content,'a+');
	        exit;
       	}
       	$this->responseMsg();
    }
	
	//信息回复
	private function responseMsg()  
    {  
        $postStr = file_get_contents('php://input');    
		
        if (!empty($postStr)){
            libxml_disable_entity_loader(true);//安全防护    
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);    
            $fromUsername = $postObj->FromUserName;    //发送方微信号，若为普通用户，则是一个OpenID
            $toUsername = $postObj->ToUserName;  		//接收方微信号,开发者微信号
            $createTime = $postObj->CreateTime;  		//消息创建时间
            $msgType = $postObj->MsgType;		//消息类型 text,image,voice,video,shortvideo,location,link
            
			$uid='0';
			$user=[];
			$_data=[];
            //关注后注册。后台设置参数
			if(C('wechat|Wechat.is_attention_reg')){
				$user=db::select('*')->from(jab.'user')->where("wechat_openid='$fromUsername'")->row();
				//不存在数据
				if(!$user){
					$uid=(new wechat)->reg($fromUsername);
					if(is_array($uid)){
						return C('wechat|errcode.'.$uid['errcode']);
					}
					hook_listen('wechat_is_attention_reg',$uid,$postStr);
				}
			}
            
            switch ($msgType)
			{
				case 'event':
					$event = $postObj->Event;
					switch($event){
						//关注公众号
						case 'subscribe':
							hook_listen('wechat_subscribe_begin',$postStr);
							//扫描带参数二维码事件
							if($postObj->EventKey){
								//事件KEY值，qrscene_为前缀，后面为二维码的参数值
								$_data['eventkey'] = $postObj->EventKey;
								//二维码的ticket，可用来换取二维码图片
								$_data['ticket'] = $postObj->Ticket;
							}
							$_data['event'] = $postObj->Event;
							db::update(jab.'user')->cols(['wechat_is_attention'=>'1'])->where("wechat_openid='$fromUsername'")->query();	
							
							//获取后台设置的参数
							$attention=unserialize(C('wechat|wechat.attention'));
							if($attention['text']){
								$data['description']=$attention['text'];
								(new wechat)->post_msg($fromUsername,$toUsername,$data,'text');
							}
							if($attention['list']){
								foreach($attention['list'] AS $row){
									if($row['picurl']){
										$row['picurl']=get_img_url($row['picurl']);
									}
									if(!$row['title'] || !$row['description'] || !$row['url'] || !$row['picurl']){
										continue;
									}
									$list[]=$row;
								}
								if($list){
									$data['list']=$list;
									(new wechat)->post_msg($fromUsername,$toUsername,$data,'news');
								}
							}
							hook_listen('wechat_subscribe_end',$postStr);
							break;
						//取消关注公众号
						case 'unsubscribe':
							hook_listen('wechat_unsubscribe',$postStr);
							$_data['event'] = $postObj->Event;
							db::update(jab.'user')->cols(['wechat_is_attention'=>'0'])->where("wechat_openid='$fromUsername'")->query();
							break;
						//用户已关注时的事件推送
						case 'SCAN':
							hook_listen('wechat_scan',$postStr);
							//事件KEY值，是一个32位无符号整数，即创建二维码时的二维码scene_id
							$_data['eventkey'] = $postObj->EventKey;
							//二维码的ticket，可用来换取二维码图片
							$_data['ticket'] = $postObj->Ticket;
							break; 
						//上报地理位置事件
						case 'LOCATION':
							hook_listen('wechat_event_location',$postStr);
							$_data['location_x'] = $postObj->Latitude; //地理位置纬度
							$_data['location_y'] = $postObj->Longitude;//地理位置经度
							$_data['precision'] = $postObj->Precision; //地理位置精度
							break;
						//自定义菜单事件
						case 'CLICK':
							hook_listen('wechat_click',$postStr);
							$_data['event'] = $postObj->Event; //事件类型，VIEW
							//事件KEY值，与自定义菜单接口中KEY值对应
							$_data['eventkey'] = $postObj->EventKey; 
							break;
						//点击菜单跳转链接时的事件推送
						case 'VIEW':
							hook_listen('wechat_view',$postStr);
							$_data['event'] = $postObj->Event; //事件类型，VIEW
							//事件KEY值，设置的跳转URL
							$_data['eventkey'] = $postObj->EventKey; 
							break; 
					}
				break;
				//文本消息
				case 'text':
					hook_listen('wechat_text_begin',$postStr);
					$_data['content'] = $postObj->Content;
			       	$_data['msgid'] = $postObj->MsgId; //消息id，64位整型
			       	$content=$this->replace_specialChar($postObj->Content);
			       	$reply=$this->reply($content);
			       	if($reply['state']=='1' || $reply['state']=='0'){
			       		(new wechat)->post_msg($fromUsername,$toUsername,$reply);
			       	}else{
			       		$data['list']['0']=$reply;
			       		(new wechat)->post_msg($fromUsername,$toUsername,$data,'news');
			       	}
					hook_listen('wechat_text_end',$postStr);
					break;
				//图片消息
				case 'image':
					hook_listen('wechat_image',$postStr);
					$_data['msgid'] = $postObj->MsgId; //消息id，64位整型
					$_data['mediaid'] = $postObj->MediaId; //图片消息媒体id，可以调用多媒体文件下载接口拉取数据。
					$_data['picurl'] = $postObj->PicUrl; //图片链接（由系统生成）
					break;
				//语音消息
				case 'voice':
					hook_listen('wechat_voice_begin',$postStr);
					$_data['msgid'] = $postObj->MsgId; //消息id，64位整型
					$_data['mediaid'] = $postObj->MediaId; //语音消息媒体id，可以调用多媒体文件下载接口拉取该媒体
					$_data['content']=$postObj->Recognition; //语音识别结果，UTF8编码。如果存在则表示识别出来了
					$_data['format'] = $postObj->Format; //语音格式，如amr，speex等
					if($_data['content']){
						$content=$this->replace_specialChar($_data['content']);
						$reply=$this->reply($content);
				       	if($reply['state']=='1' || $reply['state']=='0'){
				       		(new wechat)->post_msg($fromUsername,$toUsername,$reply);
				       	}else{
				       		$data['list']['0']=$reply;
				       		(new wechat)->post_msg($fromUsername,$toUsername,$data,'news');
				       	}
					}
					hook_listen('wechat_voice_end',$postStr);
					break;
				//视频消息
				case 'video':
					hook_listen('wechat_video',$postStr);
					$_data['msgid'] = $postObj->MsgId;
					$_data['mediaid'] = $postObj->MediaId;
					$_data['thumbmediaid'] = $postObj->ThumbMediaId;
					break;
				//小视频消息
				case 'shortvideo':
					hook_listen('wechat_shortvideo',$postStr);
					$_data['msgid'] = $postObj->MsgId; // 消息id，64位整型
					$_data['mediaid'] = $postObj->MediaId; //	视频消息媒体id，可以调用多媒体文件下载接口拉取数据。
					$_data['thumbmediaid'] = $postObj->ThumbMediaId;//视频消息缩略图的媒体id，可以调用多媒体文件下载接口拉取数据。
					break;
				//地理位置消息
				case 'location':
					hook_listen('wechat_location',$postStr);
					$_data['msgid'] = $postObj->MsgId;
					$_data['location_x'] = $postObj->Location_X; //地理位置维度
					$_data['location_y'] = $postObj->Location_Y; //地理位置经度
					$_data['scale'] = $postObj->Scale; //地图缩放大小
					$_data['label'] = $postObj->Label; //地理位置信息
					break;
				//链接消息
				case 'link':
					hook_listen('wechat_link',$postStr);
					$_data['title'] = $postObj->Title; //消息标题
					$_data['content'] = $postObj->Description; //	消息描述
					$_data['url'] = $postObj->Url; //消息链接
					$_data['msgid'] = $postObj->MsgId; //消息id，64位整型
					break;
				case 'file':
					hook_listen('wechat_file',$postStr);
					return ;
					break;
           	}
           	//存在$_data数组时，才往里面插入消息;
           	if(isset($_data)){
           		if(!$user && !$uid){
           			//获取用户在本站注册的数据
           			$user=db::select('*')->from(jab.'user')->where("wechat_openid='$fromUsername'")->row();
           		}
           		//这个uid是首次注册得来的。如果是后续则不会存在这个变量
           		if($uid !='0' && is_numeric($uid)){
           			$user=db::select('*')->from(jab.'user')->where("uid='$uid'")->row();
           		}
           		//如果还是不存在则向微信请求用户信息
           		if(!$user){
           			$userinfo=(new wechat)->get_wechat_userinfo($fromUsername);
           			$username = str_replace(array('|',' ','',"'",'"','/','*',',','~',';','<','>','$',"\\","\r","\t","\n","`","!","?","%","^"),'',$userinfo['nickname']);
					$user['uid']='0';
           			$user['username']=htmlspecialchars($username);
           		}
           		$_data['openid']=$fromUsername;
           		$_data['uid']=$user['uid'];
           		$_data['username']=$user['username'];
           		$_data['msgtype']=$msgType;
           		$_data['posttime']=NOWTIME;
           		db::insert(jab.'plugin_wechat_record')->cols($_data)->query();
           	}
        }
    }
	
	
	//签名验证
	private function checkSignature()
	{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
		$token = C(MODULE.'.token');
        if(!$token){
            return false;
        }
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
	
	private function reply($keyword){
		$data=db::select('*')->from(jab.'plugin_wechat_reply')->where("title LIKE '%$keyword%' ")->row();
		if($data){
			if($data['picurl'] && $data['url']){
				$data['picurl']=get_img_url($data['picurl']);
				$data['state']='2';
			}else{
				$data['state']='1';
			}
		}else{
			$data=[
				'state'=>'0',
				'description'=>C('wechat|Wechat.noanswer')
			];
		}
		return $data;
	}
	
	private function replace_specialChar($str){
		$regex = "/\/|\～|\，|\。|\！|\？|\“|\”|\【|\】|\『|\』|\：|\；|\《|\》|\’|\‘|\ |\·|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
	    return preg_replace($regex,"",$str);
	}
}
?>